package com.newlink.building.main.fragment

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.newlink.building.library_rino.ConnectionController
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.event.CallCreateActionBean
import com.newlink.building.common_base.event.CallCreateBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TokenVo
import com.newlink.building.common_base.ext.dividerGridSpace
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.PropertyManagerData
import com.newlink.building.common_base.model.bean.RoomData
import com.newlink.building.common_base.model.bean.UnitData
import com.newlink.building.common_base.model.bean.UnitTabData
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.main.R
import com.newlink.building.main.adapter.Module_Main_CategorySecondItemAdapter
import com.newlink.building.main.databinding.FragmentCategorySecondBinding
import com.newlink.building.main.mvp.contract.Module_Main_ResidentContract
import com.newlink.building.main.mvp.presenter.Module_Main_ResidentPresenter
import com.newlink.building.main.ui.Module_Main_RoomUserActivityNL
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub

const val KEY_UNIT_ID = "unitId"

/**
 * @author mingyan.su
 * @date   2023/3/19 22:31
 * @desc   分类item
 */
class CategorySecondFragment : BaseMvpFragment<Module_Main_ResidentContract.View, Module_Main_ResidentContract.Presenter>(),
    Module_Main_ResidentContract.View {

    private var mAdapter = Module_Main_CategorySecondItemAdapter()
    private lateinit var mBinding: FragmentCategorySecondBinding
    private var mUnitId = ""
    private var mUnitTabData: UnitTabData? = null
    private var mPropertyManagerData: PropertyManagerData? = null
    var localChannelName: String = ""
    var tokenVo: TokenVo? = null

    companion object {
        fun newInstance(tabData: UnitTabData): CategorySecondFragment {
            val fragment = CategorySecondFragment()
            val bundle = Bundle()
            bundle.putSerializable(KEY_UNIT_ID, tabData)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun attachLayoutRes(): View {
        mBinding = FragmentCategorySecondBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView(view: View) {
        // 分类页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("CategorySecondFragment", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(mUnitId.hashCode())

        mBinding.recyclerView?.apply {
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = mAdapter
            dividerGridSpace(2, 8.0f, true)
        }
        mAdapter.onItemClickListener = { _: View, position: Int ->
            var item = mAdapter.getItem(position)
            if (item is RoomData) {
                Intent(requireActivity(), Module_Main_RoomUserActivityNL::class.java).run {
                    putExtra("mRoomData", item)
                    startActivity(this)
                }
            } else if (item is PropertyManagerData) {
                // 物业管理员通话请求时的混淆
                Module_Obfuscation_ObfuscationHelper.beforeNetworkRequest(
                    item.toString(),
                    mapOf("type" to "PROPERTY_CALL")
                )
                Module_Obfuscation_ObfuscationInvoker.invokeSpecific(6, item.hashCode())

                mPropertyManagerData = item

                if (!PermissionHelper.required(requireContext())
                        .hasPermission(Manifest.permission.RECORD_AUDIO)
                ) {
                    checkAudioPermission()
                } else {
//                    makeCall()
                    sendCreateChannelEvent()
                }
//                Intent(requireActivity(), PropertyManagerDetailActivity::class.java).run {
//                    putExtra("mManagerData", mAdapter.getItem(position) as PropertyManagerData)
//                    startActivity(this)
//                }
            }


//            if (item != null && !item.link.isNullOrEmpty()) {
//                MainServiceProvider.toArticleDetail(
//                    context = requireContext(),
//                    url = item.link!!,
//                    title = item.title ?: ""
//                )
//            }
        }
        coreContext.core.addListener(coreListener)
    }

    override fun createPresenter(): Module_Main_ResidentContract.Presenter = Module_Main_ResidentPresenter()

    override fun initData() {
//        mUnitId = arguments?.getString(KEY_UNIT_ID, "").orEmpty()
        mUnitTabData = arguments?.getSerializable(KEY_UNIT_ID) as UnitTabData?

        super.initData()


//        val list = mutableListOf(RoomData(listJson,listJson,listJson))
//        val list = listJson?.toBeanOrNull<MutableList<CategoryItem.CategorySecondItem>>()
//        mAdapter.setData(list)
//        if (list.isNullOrEmpty()) {
//            mBinding.viewEmptyData?.visible()
//        } else {
//            mBinding.viewEmptyData?.gone()
//        }
    }

    override fun lazyLoad() {
        mUnitTabData?.let {
            when (it.type) {
                0 -> {
                    val unitData = mUnitTabData as UnitData?
                    unitData?.let {
                        mPresenter?.getRoomList(accessToken, unitData.id, "")
                    }
                }

                1 -> {
                    mUnitTabData?.let {
                        mPresenter?.getPropertyUserList(accessToken, mUnitTabData!!.prjId, "")
                    }
                }

                else -> {}
            }
        }

    }

    override fun getUnitListSuccess(data: MutableList<UnitData>) {
    }

    override fun getRoomListSuccess(data: MutableList<RoomData>) {
        if (!data.isNullOrEmpty()) {
            mAdapter.setData(data)
        } else {
            mBinding.viewEmptyData.visibility = View.VISIBLE
        }
    }

    override fun getPropertyUserListSuccess(data: MutableList<PropertyManagerData>) {
        val filteredData = data.filter { it.id != userId.toString() }
        if (!filteredData.isNullOrEmpty()) {
            mAdapter.setData(filteredData)
        } else {
            mBinding.viewEmptyData.visibility = View.VISIBLE
        }
    }

    private fun checkAudioPermission() {
        val message = getString(
            R.string.common_permission_audio_message,
            getString(R.string.common_permission_to_setting),
            getString(R.string.common_permission_microphone)
        )
        CustomMessageDialog(requireContext()).setTitle(getString(R.string.common_permission_title))
            .setMessage(message)

            .setNegativeButton(
                getString(R.string.cancel_dialog_custom)
            ) { dialog ->
                dialog.dismiss()
                showToast(getString(R.string.common_permission_cancel_alert))
            }
            .setPositiveButton(
                getString(R.string.common_permission_to_setting)
            ) { dialog ->
                requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                dialog.dismiss()
            }.show()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            for (i in permissions.indices) {
                when (permissions[i]) {
                    Manifest.permission.RECORD_AUDIO -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //给了权限
                        sendCreateChannelEvent()
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                requireActivity(),
                                Manifest.permission.RECORD_AUDIO
                            )
                        ) {
                            //拒绝
                            checkAudioPermission()
                        } else {
                            openAppSettings()
                        }
                    }
                }
            }
        }
    }

    private fun openAppSettings() {
        val intent = Intent()
        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        val uri = Uri.fromParts("package", requireActivity().packageName, null)
        intent.data = uri
        startActivity(intent)
    }

    fun sendCreateChannelEvent() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        val sipMsgEvent = MessageEvent(
            TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER,
            CallCreateActionBean(aid = agoraId)
        )
        EventBus.getDefault().post(sipMsgEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER -> {
                val callCreateBean = event.msgContent as CallCreateBean?
                localChannelName = callCreateBean?.data?.rtcToken?.channelName.orEmpty()
                tokenVo = callCreateBean?.data
                makeCall()
            }
        }
    }

    private val coreListener = object : CoreListenerStub() {
        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String,
        ) {
            when (state) {
                /**
                 * 由于在coreContext里OutgoingInit时会确保清除ChannelName,家庭成员呼叫是自己创建的ChannelName需要重新设置一下
                 */
                Call.State.OutgoingProgress -> {
                    if (localChannelName.isNotEmpty()) {
                        ConnectionController.getInstance(requireContext())
                            .setRemoteChannelName(localChannelName)
                    }
                    if (tokenVo != null) {
                        ConnectionController.getInstance(requireContext())
                            .convert2AgoraUserToken(tokenVo, agoraId, agoraAppId)
                    }
                }

                else -> {}
            }
        }
    }

    private fun makeCall() {
        Module_Phone_VoipController.get()
            .makeAudioCall(mPropertyManagerData?.aid.toString(), mPropertyManagerData?.name)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        coreContext.core.removeListener(coreListener)
    }
}